import 'package:flutter/foundation.dart';
import 'learning_item.dart';
import 'user_preference.dart';
import 'recommendation_service.dart';
import 'learning_data_service.dart';

/// 共享推荐数据管理服务
class SharedRecommendationService {
  static final SharedRecommendationService _instance = SharedRecommendationService._internal();
  
  factory SharedRecommendationService() => _instance;
  
  SharedRecommendationService._internal();
  
  // 共享的推荐数据
  List<LearningItem> _recommendedItems = [];
  
  // 用户偏好
  UserPreference _userPreference = UserPreference();
  
  // 所有项目数据
  List<LearningItem> _allItems = [];
  
  // 数据加载状态
  bool _isDataLoaded = false;
  
  // 监听器列表
  final List<VoidCallback> _listeners = [];
  
  /// 获取单例实例
  static SharedRecommendationService get instance => _instance;
  
  /// 获取推荐项目列表
  List<LearningItem> get recommendedItems => _recommendedItems;
  
  /// 获取用户偏好
  UserPreference get userPreference => _userPreference;
  
  /// 获取所有项目
  List<LearningItem> get allItems => _allItems;
  
  /// 检查数据是否已加载
  bool get isDataLoaded => _isDataLoaded;
  
  /// 更新推荐数据
  void updateRecommendations(List<LearningItem> items) {
    _recommendedItems = items;
    _notifyListeners();
  }
  
  /// 更新用户偏好
  void setUserPreference(UserPreference preference) {
    _userPreference = preference;
    _notifyListeners();
  }
  
  /// 根据用户选择更新偏好
  UserPreference updateUserPreferenceFromSelection(
    UserPreference currentPreference,
    int? selectedGrade,
    String? selectedSubject,
    String? selectedModule,
  ) {
    final updatedPreference = RecommendationService.updateUserPreference(
      currentPreference,
      selectedGrade,
      selectedSubject,
      selectedModule,
    );
    setUserPreference(updatedPreference);
    return updatedPreference;
  }
  
  /// 更新所有项目数据
  void updateAllItems(List<LearningItem> items) {
    _allItems = items;
    _isDataLoaded = true;
    _notifyListeners();
  }
  
  /// 从数据源加载所有项目数据
  Future<void> loadAllItems() async {
    if (_isDataLoaded) {
      return;
    }
    
    try {
      final items = await LearningDataService.loadLearningItems();
      updateAllItems(items);
    } catch (e) {
      print('Error loading items in SharedRecommendationService: $e');
      // Even if there's an error, mark as loaded to prevent infinite retries
      _isDataLoaded = true;
      _notifyListeners();
    }
  }
  
  /// 生成新的推荐数据
  Future<List<LearningItem>> generateRecommendations({int count = 20}) async {
    // 确保数据已加载
    if (!_isDataLoaded) {
      await loadAllItems();
    }
    
    // 确保有数据可以推荐
    if (_allItems.isEmpty) {
      print('No items available for recommendation');
      return [];
    }
    
    final recommended = RecommendationService.recommendItems(
      _allItems,
      _userPreference,
      count: count,
    );
    updateRecommendations(recommended);
    return recommended;
  }
  
  /// 基于用户偏好推荐学习内容（排除已展示的项目）
  Future<List<LearningItem>> recommendItemsWithExclusion(
    Set<String> excludedIds, {
    int count = 10, // 默认推荐数量
  }) async {
    // 确保数据已加载
    if (!_isDataLoaded) {
      await loadAllItems();
    }
    
    // 确保有数据可以推荐
    if (_allItems.isEmpty) {
      print('No items available for recommendation');
      return [];
    }
    
    return RecommendationService.recommendItemsWithExclusion(
      _allItems,
      _userPreference,
      excludedIds,
      count: count,
    );
  }
  
  /// 添加监听器
  void addListener(VoidCallback listener) {
    _listeners.add(listener);
  }
  
  /// 移除监听器
  void removeListener(VoidCallback listener) {
    _listeners.remove(listener);
  }
  
  /// 通知所有监听器
  void _notifyListeners() {
    for (var listener in _listeners) {
      listener();
    }
  }
}